package com.xtedu.examproject.controller;

import com.xtedu.examproject.entity.Menu;
import com.xtedu.examproject.service.MenuService;
import com.xtedu.examproject.util.NavManagementUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/delnavigation/*")
public class DelNavigationServlet extends HttpServlet {
    private MenuService menuService;
    private NavManagementUtil navManagementUtil;

    @Override
    public void init() throws ServletException {
        menuService = new MenuService();
        navManagementUtil = new NavManagementUtil();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取菜单数据并设置到request中
            List<Menu> menus = menuService.findAll();
            request.setAttribute("menuItems", menus);

            // 转发到JSP页面
            request.getRequestDispatcher("/WEB-INF/views/delnavigation.jsp").forward(request, response);
        } catch (Exception e) {

            request.setAttribute("errorMessage", "获取菜单数据失败: " + e.getMessage());
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            String idParam = request.getParameter("id");
            if (idParam != null && !idParam.trim().isEmpty()) {
                int id = Integer.parseInt(idParam.trim());// 获取菜单ID
                Menu menu = menuService.findById(id);// 根据ID查询菜单

                if (menu != null) {
                    boolean success = menuService.delete(menu) > 0 && navManagementUtil.delRoleMenu(id);
                   navManagementUtil.updateSessionMenu(request);// 更新session中的菜单数据
                    out.write("{\"success\": " + success + "}");
                } else {
                    out.write("{\"success\": false, \"message\": \"菜单不存在\"}");
                }
            } else {
                out.write("{\"success\": false, \"message\": \"缺少菜单ID参数\"}");
            }

        } catch (Exception e) {
            log("处理删除菜单请求时发生错误", e);
            out.write("{\"success\": false, \"message\": \"服务器错误\"}");
        }
    }

}